package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book){
        boolean save = bookService.save(book);
        return new Result(save?Code.SAVE_OK:Code.SAVE_ERR,null,save?"添加成功":"添加失败");
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        //System.out.println("book = " + book);
        boolean save = bookService.update(book);
        return new Result(save?Code.UPDATE_OK:Code.UPDATE_ERR,null,save?"修改成功":"修改失败");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = bookService.delete(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,null,flag?"删除成功":"删除失败");
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.FIND_OK :Code.FIND_ERR;
        String msg = book != null ? "查找成功" :"数据查询失败,请稍后重试";
        return new Result(code,book,msg);
    }

    @GetMapping
    public Result getList(){
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.FIND_OK :Code.FIND_ERR;
        String msg = bookList != null ? "查找成功" :"数据查询失败,请稍后重试";
        return new Result(code,bookList,msg);
    }
}
